package com.jacoblyu.factoryrunner.ui.views

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.jacoblyu.factoryrunner.data.TestResultManager
import com.jacoblyu.factoryrunner.ui.theme.*

@Composable
fun HomeView(navController: NavController, testResult: String? = null, testName: String? = null) {
    // 获取Context用于TestResultManager
    val context = LocalContext.current
    val testResultManager = remember { TestResultManager(context) }
    // 获取屏幕配置信息
    val configuration = LocalConfiguration.current
    val screenWidthDp = configuration.screenWidthDp.dp
    val screenHeightDp = configuration.screenHeightDp.dp
    
    // 根据屏幕尺寸计算比例
    val isLargeScreen = screenWidthDp.value > 1500 // 判断是否为1920x1200分辨率
    
    // 根据屏幕大小调整字体和间距
    val titleFontSize = if (isLargeScreen) 36.sp else 28.sp
    val cardFontSize = if (isLargeScreen) 24.sp else 18.sp
    val buttonFontSize = if (isLargeScreen) 26.sp else 20.sp
    val cardHeight = if (isLargeScreen) 120.dp else 90.dp
    val cardPadding = if (isLargeScreen) 20.dp else 16.dp
    val verticalSpacing = if (isLargeScreen) 16.dp else 12.dp
    val horizontalSpacing = if (isLargeScreen) 20.dp else 16.dp
    val buttonHeight = if (isLargeScreen) 80.dp else 60.dp
    val buttonWidth = if (isLargeScreen) 300.dp else 220.dp
    
    // 测试项及其状态
    val testItems = listOf(
        "USB测试" to "usb_test",
        "屏幕测试" to "screen_test",
        "麦克风喇叭测试" to "audio_test",
        "Wi-Fi测试" to "wifi_test",
        "蓝牙测试" to "bluetooth_test",
        "照明测试" to "light_test",
        "前置摄像头测试" to "front_camera_test",
        "高拍摄像头测试" to "high_camera_test",
        "TF卡测试" to "tfcard_test"
    )
    
    // 从TestResultManager加载测试结果
    var testStatuses by remember {
        mutableStateOf(testResultManager.getAllTestResults())
    }
    
    // 更新测试状态（如果有测试结果返回）
    LaunchedEffect(testResult, testName) {
        if (testResult != null && testName != null) {
            // 保存测试结果到TestResultManager
            testResultManager.saveTestResult(testName, testResult)
            // 更新本地状态
            testStatuses = testStatuses.toMutableMap().apply {
                put(testName, testResult)
            }
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFFF5F5F5))
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        // 标题区域
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 16.dp, bottom = 24.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "整机产测程序",
                fontSize = titleFontSize,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF1976D2)
            )
            Text(
                text = "V1.0.0-9cfb92f",
                fontSize = if (isLargeScreen) 18.sp else 14.sp,
                fontWeight = FontWeight.Normal,
                color = Color(0xFF757575)
            )
        }
        
        // 测试项目卡片区域
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(verticalSpacing)
        ) {
            // 将9个测试项目分为3行，每行3个
            for (row in 0..2) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(horizontalSpacing, Alignment.CenterHorizontally)
                ) {
                    for (col in 0..2) {
                        val index = row * 3 + col
                        if (index < testItems.size) {
                            val (itemName, _) = testItems[index]
                            val status = testStatuses[itemName] ?: "未测试"
                            
                            val statusColor = when (status) {
                                "通过" -> Color(0xFF4CAF50)
                                "不通过" -> Color(0xFFF44336)
                                "测试中" -> Color(0xFFFF9800)
                                else -> Color.Gray
                            }
                            
                            Card(
                                modifier = Modifier
                                    .weight(1f)
                                    .height(cardHeight),
                                colors = CardDefaults.cardColors(
                                    containerColor = when (status) {
                                        "通过" -> Color(0xFFC8E6C9) // 淡绿色
                                        "不通过" -> Color(0xFFF8BBD0) // 粉红色
                                        else -> Color.White
                                    },
                                    contentColor = Color.Black
                                ),
                                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
                                onClick = {
                                    // 点击卡片直接导航到对应的测试页面
                                    val route = when (itemName) {
                                        "USB测试" -> "usb_test"
                                        "屏幕测试" -> "screen_test"
                                        "麦克风喇叭测试" -> "audio_test"
                                        "Wi-Fi测试" -> "wifi_test"
                                        "蓝牙测试" -> "bluetooth_test"
                                        "照明测试" -> "light_test"
                                        "前置摄像头测试" -> "front_camera_test"
                                        "高拍摄像头测试" -> "high_camera_test"
                                        "TF卡测试" -> "tfcard_test"
                                        else -> "home"
                                    }
                                    navController.navigate(route)
                                }
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .padding(cardPadding),
                                    horizontalArrangement = Arrangement.SpaceBetween,
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Text(
                                        text = itemName,
                                        fontSize = cardFontSize,
                                        fontWeight = FontWeight.Medium
                                    )
                                    
                                    Box(
                                        modifier = Modifier
                                            .size(if (isLargeScreen) 24.dp else 18.dp)
                                            .background(
                                                when (status) {
                                                    "通过" -> Color(0xFF4CAF50) // 绿色
                                                    "失败" -> Color(0xFFF44336) // 红色
                                                    "测试中" -> Color(0xFFFF9800) // 橙色
                                                    else -> Color(0xFF9E9E9E) // 灰色
                                                },
                                                RoundedCornerShape(12.dp)
                                            ),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        Text(
                                            text = when (status) {
                                                "通过" -> "✓"
                                                "失败" -> "✗"
                                                "测试中" -> "..."
                                                else -> "○"
                                            },
                                            color = Color.White,
                                            fontSize = if (isLargeScreen) 16.sp else 12.sp,
                                            fontWeight = FontWeight.Bold
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        
        // 开始测试按钮
        Button(
            onClick = {
                // 导航到USB测试页面
                navController.navigate("usb_test")
            },
            modifier = Modifier
                .width(buttonWidth)
                .height(buttonHeight)
                .padding(bottom = 24.dp),
            colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF4CAF50))
        ) {
            Text(
                text = "开始测试",
                fontSize = buttonFontSize,
                color = Color.White,
                fontWeight = FontWeight.Bold
            )
        }
    }
}

@Preview(showBackground = true, widthDp = 1280, heightDp = 800)
@Composable
fun DefaultPreview() {
    FactoryrunnerTheme {
        val navController = rememberNavController()
        HomeView(navController = navController)
    }
}

@Preview(showBackground = true, widthDp = 1920, heightDp = 1200)
@Composable
fun LargeScreenPreview() {
    FactoryrunnerTheme {
        val navController = rememberNavController()
        HomeView(navController = navController)
    }
}